﻿using IdentityModel.Client;
using LXYYY.ids4;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace LXYYY.Ids4o
{
    public class Ids4 : IIds4
    {
        private IConfiguration _configuration;
        public Ids4(IConfiguration configuration)
        {
            this._configuration = configuration;
        }
        public async Task<string> GetIdsTolenAsync(string LoginName, string Loginpwd)
        {
            var client = new HttpClient();
            var idsToKenUrl = this._configuration.GetSection("AuthServer:Authority").Value;
            var AppClientId = this._configuration.GetSection("AuthServer:AppClientId").Value;
            var AppClientSecret = this._configuration.GetSection("AuthServer:AppClientSecret").Value;
            var disco = client.GetDiscoveryDocumentAsync(idsToKenUrl);
            var tokenResponse = await client.RequestPasswordTokenAsync(
                new PasswordTokenRequest
                {
                    Address=disco.Result.TokenEndpoint,
                    ClientId=AppClientId,
                    ClientSecret=AppClientSecret,
                    UserName=LoginName,
                    Password=Loginpwd
                }
                );
            if (tokenResponse.IsError)
            {
                return string.Empty;
            }
            return tokenResponse.AccessToken;
        }
    }
}
